import axios from 'axios'
import mitt from 'mitt'
import { setHeaderLoginQuery, setHeaderSK } from './sk'
import { getUrlQuery, traceHandle, useUserStore } from '@/utils'

type Events = {
  notMember: { message: string }
  memberExpired: { message: string; result: any; url?: any }
  toast: { message: string }
}
export const emitter = mitt<Events>()

axios.defaults.headers.common['Authorization'] = ''
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

export const defHttp = axios.create()

export const BASEURL = '/api3/bank-go'

// 添加请求拦截器
defHttp.interceptors.request.use(
  function (config) {
    !config.data && (config.data = {})
    !config.params && (config.params = {})

    const WHITE_LIST_API: string[] = []

    if (!WHITE_LIST_API.includes(config.url!)) {
      setHeaderLoginQuery(config)
      setHeaderSK(config)
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

// 添加响应拦截器
defHttp.interceptors.response.use(
  function (response) {
    const { config = {}, data: responseData = {} }: any = response || {}

    const { url, params, data: requestBodyData } = config

    let { code, data: resultData = {}, message, msg } = responseData
    message = message || msg

    // 兼容滑块问题，如果有滑块情况直接出去
    if (responseData.repCode) {
      return responseData
    }

    if (/Network Error/i.test(message)) {
      message = '网络开小差了，请稍后再试～'
    }

    const { skToken, memberCode, channelCode, dev } = getUrlQuery()

    // 设置skToken
    if (skToken) {
      const id = `${skToken}_${memberCode}`
      // 确保 resultData 是对象类型才设置属性，避免在 webview 环境中对字符串设置属性报错
      if (resultData && typeof resultData === 'object' && !Array.isArray(resultData)) {
        resultData['skToken'] = id
      }
      localStorage.setItem(`skToken_${channelCode}_${memberCode}`, id)
    }

    // 非会员不能访问
    if (code == 200301 && dev !== 'true') {
      emitter.emit('notMember', message)
      return Promise.reject(message)
    }

    // 会员时间已过期，请重新购买会员
    if (code == 200303) {
      emitter.emit('memberExpired', { message, result: resultData, url })
      useUserStore().change({ expired: true })
      return Promise.reject(message)
    }

    // 风控验签
    if (code == 999999999) {
      if (!useUserStore().userInfo.captcha) {
        useUserStore().change({ captcha: true })
      }
    }

    let isHideToast =
      response.config?.params?.isHideToast ||
      responseData?.isHideToast ||
      responseData?.data?.isHideToast
    if (requestBodyData) {
      try {
        const parsedRequestData = JSON.parse(requestBodyData)
        isHideToast =
          response.config?.params?.isHideToast ||
          parsedRequestData?.isHideToast ||
          parsedRequestData?.data?.isHideToast
      } catch (e) {
        console.log('e', e)
      }
    }
    if (!isHideToast && params) {
      isHideToast = params.isHideToast
    }

    if (code != 0) {
      if (!isHideToast && message) emitter.emit('toast', { message })

      if (url === '/api3/bank-go/api/v3p5/receive/async/create') {
        traceHandle({
          message: 'week-active-error-axios',
          title: '周周选活动',
          eventName: '监听抢购异常axios',
          errorData: responseData,
        })
      }

      return Promise.reject(responseData)
    }

    return resultData
  },
  function (error) {
    let { message } = error

    if (error && error.response) {
      const {
        response: { status },
      } = error
      if ([500, 502, 504].includes(status)) {
        emitter.emit('toast', { message: '活动太火爆，请稍后重试' })
        return Promise.reject(error)
      }
    }

    if (/Network Error/i.test(message) || error?.response?.status !== 200) {
      message = '网络开小差了，请稍后再试～'
    }

    emitter.emit('toast', { message })
    return Promise.reject(error)
  },
)
